<template>
	<view class="login" :style="{ direction: $store.state.dir }">
		<logo></logo>

		<input-item :name="$t('login.username')" icon="icon-user">
			<input v-model="name" class="input" type="text" />
		</input-item>
		<input-item :name="$t('login.password')" icon="icon-unlock">
			<input v-model="password" class="input" type="text" password />
		</input-item>
		<view class="login-button">
			<u-button @click="handleLogin" type="primary" size="large" shape="circle"
				:text="$t('login.loginBtn')"></u-button>
			<br />
			<!-- <view>
				<u-button @click="auth" type="primary" icon="google" size="large" shape="circle"
					:text="$t('login.loginBtnGoogle')"></u-button>
			</view> -->
			<u-divider text="Or"></u-divider>
			<!-- 	<u-button @click="handleRegButton3" type="primary" size="large" shape="circle" plain=""
				:text="$t('login.regBtn')"></u-button> -->
			<u-button @click="handleRegButton2" type="primary" size="large" shape="circle" plain=""
				:text="$t('login.regBtn')"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		APP_ROLE,
		CurrentRole
	} from '../../config';
	import {
		showFailure,
		showMessage,
		showSuccess
	} from '../../lib/helper';
	import {
		login,
		googleLogin
	} from '../../lib/service';
	import {
		client
	} from "../../utils/utils";
	import {
		emConnect
	} from '@/EaseIM/emApis';

	export default {
		data() {
			return {
				name: '',
				password: '',
				isRotate: false, //是否加载旋转
				isFocus: true, // 是否聚焦
				client_id: '412561318887-u244ikgmdlu1b89ntn7oqvh4aafh2bfi.apps.googleusercontent.com',
				client_secret: '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'
			};
		},
		mounted() {},
		onLoad(options) {
			this.getUserInfo(options)
		},
		methods: {
			getUserInfo(options) {
				let _this = this;
				let code = ''
				// #ifdef APP-PLUS
				code = options.code
				// #endif
				// #ifdef H5
				const urlParams = new URLSearchParams(window.location.search);
				code = urlParams.get('code');
				// #endif
				if (!code) {
					return;
				}
				// 用授权码交换访问令牌地址
				const tokenEndpoint = 'https://oauth2.googleapis.com/token';
				const requestBody = new URLSearchParams();
				requestBody.append('code', code);
				// 你的 Google OAuth 客户端 ID
				requestBody.append('client_id', this.client_id);
				// 你的Google OAuth 客户端密钥
				requestBody.append('client_secret', this.client_secret);
				requestBody.append('redirect_uri', 'https://anta123.com/pages/login/login');
				requestBody.append('grant_type', 'authorization_code'); //这些参数在之前配置的有，看前面的代码
				fetch(tokenEndpoint, {
						method: 'POST',
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded',
						},
						body: requestBody
					})
					.then(response => response.json())
					.then(data => {
						// 获得token令牌的信息
						const accessToken = data.access_token;
						// 调用获取用户信息接口
						fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
								headers: {
									Authorization: `Bearer ${accessToken}`
								}
							})
							.then(response => response.json())
							.then(userInfo => {
								const {
									name,
									email,
									picture,
									id: googleid
								} = userInfo
								const params = {
									name,
									email,
									picture,
									googleid
								}
								uni.showLoading();
								_this.handleGoogleLogin(params)
								
							})

					})
			},
			handleGoogleLogin(params){
				googleLogin(params).then(res => {
					uni.hideLoading();
					showSuccess();
					this.$store.dispatch('setUser', {
						...res.data.user,
						token: res.data.token,
						imtoken: res.data.imtoken,
						impass: res.data.impass,
						imuser: res.data.imuser
					});
					// uni.navigateBack()
					uni.switchTab({
						url: "/pages/index/index"
					})
					if (res.data && res.data.imtoken) {
						this.loginWithPhoneNumber(res.data)
					}
				}).catch((err) => {
					uni.hideLoading();
					showFailure();
				});
			},
			auth() {
				let _this = this;
				// 你的Google OAuth 客户端 ID
				const clientId = this.client_id;
				// 重定向 URI
				const redirectUri = 'https://anta123.com/pages/login/login';
				// 请求的权限范围，可以根据需求修改
				const scope = 'email profile';
				// 用于防止跨站请求伪造（CSRF）攻击，可以不设置，可以随心设置
				const state = '';
				// 授权响应类型，表示要求返回授权码
				const responseType = 'code';
				const grantType = 'authorization_code';
				//&prompt=login 把它加到window.authUrl的末尾可以让用户每次都需要重新输入账号和密码
				const authUrl =
					`https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&state=${state}&response_type=${responseType}`;
				//点击Google登录  执行这个方法进行跳转
				console.log(authUrl,'authUrl')
				// #ifdef APP-PLUS
				uni.login({
					provider: 'google',
					scopes: 'profile email',
					success: function(loginRes) {
						console.log('loginRes////////', loginRes)
						var access_token = loginRes.authResult.access_token;
						// 登录成功
						if (loginRes.errMsg === 'login:ok') {
							uni.getUserInfo({
								provider: 'google',
								success: function(info) {
									let googleid = info.userInfo.openid;
									let {
										name,
										email,
										picture
									} = info.userInfo;
									const params = {
										name,
										email,
										picture,
										googleid
									}
									uni.showLoading();
									_this.handleGoogleLogin(params)
								},
								fail: function(err) {
									// 获取用户信息失败
									// err.code是错误码
									uni.showToast({
										title: `获取用户信息失败-错误码${JSON.stringify(err)}`,
										icon: "none",
										duration: 2000,
									});
								}
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '登录授权失败: ' + JSON.stringify(loginRes),
							});
						}
					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
						uni.showToast({
							title: `登录连接失败-错误码${err.code}`,
							icon: "none",
							duration: 2000,
						});
					}
				});
				// #endif
				// #ifdef H5
				window.location.href = authUrl
				// #endif
			},
			handleLogin() {
				if (this.isRotate) {
					//判断是否加载中，避免重复点击请求
					return false;
				}
				if (this.name.length <= 0) {
					showMessage(this.$t('message.emety.username'));
					return;
				}
				if (this.password.length <= 0) {
					showMessage(this.$t('message.emety.password'));
					return;
				}

				uni.showLoading();
				login({
						name: this.name,
						password: this.password,
						client,
						im: 1
					})
					.then((res) => {
						uni.hideLoading();
						showSuccess();
						this.$store.dispatch('setUser', {
							...res.data.user,
							token: res.data.token,
							imtoken: res.data.imtoken,
							impass: res.data.impass,
							imuser: res.data.imuser
						});
						
						if (res.data && res.data.imtoken) {
							this.loginWithPhoneNumber(res.data)
						}else{
							// uni.navigateBack({
							// 	delta:1,
              // })
              uni.switchTab({
						url: "/pages/index/index"
					})
						}
					})
					.catch((err) => {
						uni.hideLoading();
						showFailure();
					});
			},
			async loginWithPhoneNumber(data) {
				const {
					loginWithAccessToken,
					closeEaseIM
				} = emConnect();
				loginWithAccessToken(data.imuser, data.imtoken);
				this.$store.commit('SET_LOGIN_USER_BASE_INFOS', {
					imuser: data.imuser,
					impass: data.impass,
				});
				this.setEMUserLoginInfosToStorage(data.imuser, data.imtoken);

			},
			setEMUserLoginInfosToStorage(imuser, imtoken) {
				const params = {
					key: `EM_LOGIN_INFOS`,
					data: {
						imuser,
						imtoken
					},
				};
				uni.setStorage({
					...params
				});
				// uni.navigateBack({
				// 	delta:1,
        // })
        uni.switchTab({
						url: "/pages/index/index"
					})
			},
			handleRegButton1() {
				uni.navigateTo({
					url: '/pages/login/register?type=1'
				});
			},
			handleRegButton2() {
				uni.navigateTo({
					url: '/pages/login/register?type=2'
				});
			},
			handleRegButton3() {
				uni.navigateTo({
					url: '/pages/login/register?type=' + (CurrentRole == APP_ROLE.Agent ? '2' : '1')
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.login {
		padding: 0 30px;

		.login-button {
			margin-top: 20px;
		}
	}
</style>